import React, { useEffect, useState } from "react";
import { Button, Space, Table, Tag } from "antd";
import axios from "../../../api/axios";
import type { TableProps } from "antd";
import type { PopconfirmProps } from "antd";
import { message, Popconfirm } from "antd";
import { Modal } from "antd";
import { Form, Input } from "antd";
import type { FormProps } from "antd";
import useI18n from "../../../app/useI18n";
import { useThemeContext } from "../../../app/ThemeContext";
import { saveAs } from "file-saver";

// 过滤HTML标签的函数
const stripHtmlTags = (html: any): string => {
    if (!html) return "";
    if (typeof html !== "string") return String(html);
    return html.replace(/<[^>]*>/g, "").trim();
};

function Index() {
    const { t } = useI18n();
    const { theme } = useThemeContext();
    const [data, setData] = useState();
    const [cllij, setcllij] = useState(0);
    const [pageCode, setpageCode] = useState(1);
    const [pageSize, setpageSize] = useState(10);
    const [title, settitle] = useState();
    const [addForm] = Form.useForm();
    const getData = () => {
        axios.get("/list", { params: { pageCode, pageSize } }).then((res) => {
            console.log(res);
            setData(res.data.data.data);
            setcllij(res.data.data.totalCount);
        });
    };
    useEffect(() => {
        getData();
    }, [pageCode, pageSize]);
    //添加
    const [isModalOpen, setIsModalOpen] = useState(false);

    const showModal = () => {
        setIsModalOpen(true);
        settitle("添加");
        addForm.resetFields();
    };
    const handleOk = (values) => {
        setIsModalOpen(false);
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };

    const onFinish: FormProps["onFinish"] = (values) => {
        console.log("Success:", values);
        const formData = addForm.getFieldsValue();
        if (title == "添加") {
            axios.put("/list", formData);
            alert("添加成功");
            setIsModalOpen(false);
            getData();
            addForm.resetFields();
        } else {
            axios.post("/list", formData);
            alert("编辑成功");
            setIsModalOpen(false);
            getData();
            addForm.resetFields();
        }
    };

    const onFinishFailed: FormProps["onFinishFailed"] = (errorInfo) => {
        console.log("Failed:", errorInfo);
    };
    //编辑
    const bianji = (record) => {
        addForm.setFieldsValue(record);
        setIsModalOpen(true);
        settitle("编辑");
    };
    //分页
    const add = (pageCode, pageSize) => {
        setpageCode(pageCode);
        setpageSize(pageSize);
    };
    //跳转
    const click = () => {
        window.location.href = "/color";
    };
    const username = localStorage.getItem("username");
    const columns: TableProps["columns"] = [
        {
            title: t("ID"),
            dataIndex: "id",
            key: "id",
            render: (text) => <a>{stripHtmlTags(text)}</a>,
        },
        {
            title: t("商品图片"),
            dataIndex: "shopImage",
            key: "shopImage",
            render: (imageUrl) =>
                imageUrl ? (
                    <div
                        style={{ cursor: "pointer" }}
                        onClick={() => {
                            Modal.info({
                                title: (
                                    <div
                                        style={{
                                            textAlign: "center",
                                            fontSize: "18px",
                                            fontWeight: "bold",
                                            color: "var(--text-color)",
                                        }}
                                    >
                                        商品图片预览
                                    </div>
                                ),
                                content: (
                                    <div
                                        style={{
                                            textAlign: "center",
                                            padding: "20px 0",
                                        }}
                                    >
                                        <img
                                            src={imageUrl}
                                            alt="商品图片"
                                            style={{
                                                maxWidth: "100%",
                                                maxHeight: "500px",
                                                objectFit: "contain",
                                                borderRadius: "8px",
                                                boxShadow:
                                                    "0 4px 12px rgba(0,0,0,0.15)",
                                                border: "1px solid rgba(0,0,0,0.1)",
                                            }}
                                            onError={(e) => {
                                                e.currentTarget.style.display =
                                                    "none";
                                                const nextSibling = e
                                                    .currentTarget
                                                    .nextSibling as HTMLElement;
                                                if (nextSibling) {
                                                    nextSibling.style.display =
                                                        "block";
                                                }
                                            }}
                                        />
                                        <div
                                            style={{
                                                display: "none",
                                                padding: "40px",
                                                color: "#999",
                                                fontSize: "16px",
                                            }}
                                        >
                                            图片加载失败
                                        </div>
                                    </div>
                                ),
                                width: 700,
                                centered: true,
                                maskClosable: true,
                                okText: "关闭",
                                cancelText: "取消",
                                onOk: () => {},
                                style: {
                                    top: "50px",
                                },
                                bodyStyle: {
                                    padding: "20px",
                                    background: "var(--card-bg)",
                                    color: "var(--text-color)",
                                },
                            });
                        }}
                    >
                        <img
                            src={imageUrl}
                            alt="商品图片"
                            style={{
                                width: 60,
                                height: 60,
                                objectFit: "cover",
                                borderRadius: 4,
                                border: "1px solid #d9d9d9",
                                transition: "all 0.3s ease",
                                cursor: "pointer",
                            }}
                            onMouseEnter={(e) => {
                                e.currentTarget.style.transform = "scale(1.1)";
                                e.currentTarget.style.boxShadow =
                                    "0 4px 12px rgba(0,0,0,0.2)";
                                e.currentTarget.style.borderColor = "#1890ff";
                            }}
                            onMouseLeave={(e) => {
                                e.currentTarget.style.transform = "scale(1)";
                                e.currentTarget.style.boxShadow = "none";
                                e.currentTarget.style.borderColor = "#d9d9d9";
                            }}
                            onError={(e) => {
                                e.currentTarget.style.display = "none";
                                const parentElement =
                                    e.currentTarget.parentElement;
                                if (parentElement) {
                                    parentElement.innerHTML =
                                        '<span style="color: #999; font-size: 12px;">图片加载失败</span>';
                                }
                            }}
                        />
                    </div>
                ) : (
                    <span style={{ color: "#999" }}>暂无图片</span>
                ),
        },
        {
            title: t("商品名称"),
            dataIndex: "shopName",
            key: "shopName",
            render: (text) => <span>{stripHtmlTags(text)}</span>,
        },
        {
            title: t("商品地址"),
            dataIndex: "shopAddress",
            key: "shopAddress",
            render: (text) => <span>{stripHtmlTags(text)}</span>,
        },
        {
            title: t("商品描述"),
            dataIndex: "shopDescription",
            key: "shopDescription",
            render: (text) => <span>{stripHtmlTags(text)}</span>,
        },
        {
            title: t("商品电话"),
            dataIndex: "shopTel",
            key: "shopTel",
            render: (text) => <span>{stripHtmlTags(text)}</span>,
        },
        {
            title: t("商品销售量"),
            dataIndex: "shopSellCount",
            key: "shopSellCount",
            render: (text) => <span>{stripHtmlTags(text)}</span>,
        },
        {
            title: t("商品类型"),
            dataIndex: "shopType",
            key: "shopType",
            render: (text) => <span>{stripHtmlTags(text)}</span>,
        },

        {
            title: t("Action"),
            key: "action",
            render: (_, record) => (
                <Space size="middle">
                    {username === "admin" && (
                        <>
                            <Popconfirm
                                title={t("删除弹框")}
                                description={t("你确定要删除吗")}
                                onConfirm={() => confirm(record.id)}
                                onCancel={cancel}
                                okText={t("确定")}
                                cancelText={t("取消")}
                            >
                                <Button danger>{t("删除")}</Button>
                            </Popconfirm>
                            <Button onClick={() => bianji(record)}>
                                {t("修改")}
                            </Button>
                        </>
                    )}
                    <Button>{t("详情")}</Button>
                </Space>
            ),
        },
    ];
    //删除
    // const shanchu = (id) => {

    // };
    const confirm: PopconfirmProps["onConfirm"] = (id) => {
        axios.delete("/list", { params: { id } }).then((res) => {
            console.log(res);
            alert("删除成功");
            getData();
        });
        message.success("删除成功");
    };

    const cancel: PopconfirmProps["onCancel"] = (e) => {
        console.log(e);
        message.error("取消删除");
    };
    //全选

    // 导出表格为CSV
    const downloadTable = () => {
        if (!data || !Array.isArray(data) || data.length === 0) return;
        const header = columns
            .map((col) => (typeof col.title === "string" ? col.title : ""))
            .join(",");
        const rows = data
            .map((row) =>
                columns.map((col) => row[col.dataIndex] ?? "").join(",")
            )
            .join("\n");
        const csv = header + "\n" + rows;
        const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
        saveAs(blob, "table.csv");
    };

    return (
        <div
            style={{
                background: "var(--bg-color)",
                color: "var(--text-color)",
                padding: 24,
                borderRadius: 8,
                transition: "background 0.4s, color 0.4s",
            }}
        >
            <Button onClick={downloadTable} style={{ marginBottom: 16 }}>
                下载表格
            </Button>
            {username === "admin" && (
                <Button type="primary" onClick={showModal}>
                    {t("添加")}
                </Button>
            )}
            <Button onClick={click}>视频</Button>
            <Modal
                title={t(title)}
                closable={{ "aria-label": "Custom Close Button" }}
                open={isModalOpen}
                onOk={handleOk}
                onCancel={handleCancel}
            >
                <Form
                    form={addForm}
                    name="basic"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    style={{ maxWidth: 600 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                >
                    <Form.Item label={t("ID")} name="id">
                        <Input />
                    </Form.Item>
                    <Form.Item label={t("商品图片")} name="shopImage">
                        <Input
                            placeholder="请输入图片URL"
                            onChange={(e) => {
                                const url = e.target.value;
                                if (url) {
                                    // 可以在这里添加图片预览逻辑
                                    console.log("图片URL:", url);
                                }
                            }}
                        />
                    </Form.Item>
                    <Form.Item label={t("商品名称")} name="shopName">
                        <Input />
                    </Form.Item>
                    <Form.Item label={t("商品地址")} name="shopAddress">
                        <Input />
                    </Form.Item>
                    <Form.Item label={t("商品描述")} name="shopDescription">
                        <Input />
                    </Form.Item>
                    <Form.Item label={t("商品电话")} name="shopTel">
                        <Input />
                    </Form.Item>
                    <Form.Item label={t("商品销售量")} name="shopSellCount">
                        <Input />
                    </Form.Item>
                    <Form.Item label={t("商品类型")} name="shopType">
                        <Input />
                    </Form.Item>

                    <Form.Item label={null}>
                        <Button type="primary" htmlType="submit">
                            确定
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
            <Table
                columns={columns}
                dataSource={data}
                rowKey={"id"}
                pagination={{
                    total: cllij,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total) => `Total ${total} items`,
                    onChange: add,
                }}
                style={{
                    background: "var(--card-bg)",
                    color: "var(--text-color)",
                    borderRadius: 8,
                    transition: "background 0.4s, color 0.4s",
                }}
            />
        </div>
    );
}

export default Index;
